# -*- coding: utf-8 -*-
"""
Created on Sat Jul 28 09:22:02 2018

@author: 君
"""

import os
import json

#抽取每个大学在不同地区的招生计划,传入data为list，即高校原始招生信息
#返回dict{"school":[{'city':'天津','文史':20,'理工':15},{}...]} 
def getSchoolCityPlan(schoolData):

    schoolCityLists = {}
    schoolCityPlanLists = []
    for i in range(len(schoolData)):
        schoolCityPlanList = {}
        schoolCityPlanList['city'] = schoolData[i][0]['city']
        schoolCityPlanList['文史'] = 0
        schoolCityPlanList['理工'] = 0
        for j in range(len(schoolData[i])):
            b = schoolData[i][j]
            if b['subject'] == '文史':
                schoolCityPlanList['文史'] = schoolCityPlanList['文史'] + int(b['plan'])
            elif b['subject'] == '理工':
                schoolCityPlanList['理工'] = schoolCityPlanList['理工'] + int(b['plan'])
        schoolCityPlanLists.append(schoolCityPlanList)
    
    #城市文理科合并显示
    for n in range(len(schoolCityPlanLists) - 1):
        if n >= len(schoolCityPlanLists) - 1:
            break
        else:
            if schoolCityPlanLists[n]['city'] == schoolCityPlanLists[n+1]['city'] :
                schoolCityPlanLists[n]['文史'] = schoolCityPlanLists[n]['文史'] + schoolCityPlanLists[n+1]['文史']
                schoolCityPlanLists[n]['理工'] = schoolCityPlanLists[n]['理工'] + schoolCityPlanLists[n+1]['理工']
                del schoolCityPlanLists[n+1]
                n = n-1
            else:
                continue
    #将该学校的数据添加到字典schoolCityLists中
    schoolCityLists[schoolData[0][0]['school']] = schoolCityPlanLists
    return schoolCityLists

#获取目标文件夹的路径
filedir = os.getcwd()+'/data_major'
#获取当前文件夹中的文件名称列表
filenames=os.listdir(filedir)
infoSchoolCityPlanList = []
#循环遍历文件夹下面的所有文件，对其抽取有效信息
for filename in filenames:
    filepath = filedir+'/'+filename
    #打开文件，抽取有效信息部分，放在schoolData[]中
    lines = open(filepath,'r',encoding='gbk').readlines()
    data = []
    for i in range(len(lines)):
        if json.loads(lines[i])['status'] == 0:
            continue
        else:
            data.append(json.loads(lines[i])['data'])
    if data:
        infoSchoolCityPlanList.append(getSchoolCityPlan(data))
    else:
        continue

#将文件存储
f=open('dataSchoolCityPlans.json','w',encoding='gbk')
f.write(json.dumps(infoSchoolCityPlanList))
f.close()
